import { useNavigate } from "./useNavigate.ts";
import { useConfig } from "./D8dConfigProvider.tsx";
import { useApiRequest } from "./useApiRequest.ts";
import { App } from "antd";
import { useMutation } from "@tanstack/react-query";

export default () => {
  const { apiUrl, setToken, setUserInfo } = useConfig();
  const { message } = App.useApp();
  const { requestWithToken } = useApiRequest();
  const navigate = useNavigate();
  
  // 使用 useMutation 处理登出操作
  const logoutMutation = useMutation({
    mutationFn: async () => {
      if (!apiUrl.logout) {
        throw new Error("登出接口未配置");
      }
      
      // 显示退出中消息提示
      const hideLoading = message.loading('正在退出登录...', 0);
      
      try {
        return await requestWithToken({
          url: apiUrl.logout,
          method: "GET",
          data: {},
        });
      } catch (error) {
        // 出错时关闭加载消息
        hideLoading();
        throw error;
      }
    },
    onSuccess: (response) => {
      // 关闭所有消息提示
      message.destroy();
      
      if (response?.code === 200 || response?.success) {
        setToken("");
        setUserInfo(null);
        message.success("退出成功");
        navigate("/");
      } else {
        message.error(response.message || "退出失败");
      }
    },
    onError: (error) => {
      // 关闭所有消息提示
      message.destroy();
      message.error(error instanceof Error ? error.message : "退出失败");
    }
  });

  // 提供登出方法
  const logout = () => {
    logoutMutation.mutate();
  };

  return {
    logout,
    isLoggingOut: logoutMutation.isPending,
  };
};
